/*********************************************************************************
CREATED BY: SCOTT FIELDER 
CREATED DATE: 4/18/2011


REVISION HISTORY:
-

***********************************************************************************/


public with sharing class UTIL_encryption {
	
	//example of call
	//UTIL_encryption.decryptStr(UTIL_encryption.encryptStr('test'));
	
	public static string encryptStr(string s){
		
		string encryptedString;
		Encryption_Key__c x = Encryption_Key__c.getInstance();
	 	Blob key = EncodingUtil.base64Decode(x.Key__c);

        Blob data = Blob.valueOf(s);
        String b64Data = EncodingUtil.base64Encode(data);
        Blob encryptedData = Crypto.encryptWithManagedIV('AES128', key, data);
        
        encryptedString = EncodingUtil.base64Encode(encryptedData);
        
        system.debug('********encryptedString ' + encryptedString); 
        return encryptedString;
		
	}
	
	public static string decryptStr(string s){
		
		string decryptedString;
		Encryption_Key__c x = Encryption_Key__c.getInstance();
	 	Blob key = EncodingUtil.base64Decode(x.Key__c);
		
		Blob b = EncodingUtil.base64Decode(s);
		
		Blob decryptedData = Crypto.decryptWithManagedIV('AES128', key, b);
        String b64Decrypted = EncodingUtil.base64Encode(decryptedData);
        
        system.debug('*****s: '+ s);
        system.debug('*****decryptedData.toString()'+ decryptedData.toString());
        
        decryptedString = decryptedData.toString();
         
        return decryptedString;
		
	}
	
		
	/***********************************************************
	* 						TEST METHODS
	***********************************************************/
	
	static testMethod void test_doFBAuthToken(){
		
		test.startTest();
		
		Encryption_Key__c x = Encryption_Key__c.getInstance();
		
		if(x == null) {
            x = new Encryption_Key__c(SetupOwnerId = UserInfo.getOrganizationId());
        }
        
        x.OF__Key__c = '11111111111111111111111';
        
        
        Database.upsert(x); 
		
		string teststr = 'test';
		
		string enc = UTIL_Encryption.encryptStr(teststr);
		
		string dec = UTIL_Encryption.decryptStr(enc);
		
		
		
		test.stopTest();
		
		system.assert(teststr == dec);
	}
	
	

}